package com.lw.pc;

import java.time.LocalDate;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LW
 * @2020/8/19 14:15
 */
public class C {

    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                data3.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                data3.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 100; i++) {
                data3.printC();
            }
        },"C").start();

    }
}

class Data3{
    private int num=1;
    Lock lock = new ReentrantLock();
    //多个监视器来判断要唤醒的是哪一个
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();


    //A执行完调用B，B执行完调用C，C执行完调用A
    public void printA(){
        try {
            lock.lock();
            //真正定位方法唤醒   的是num的值  作为标志位
            while (num!=1){
                condition1.await();//condition1等待
            }
            System.out.println(Thread.currentThread().getName()+"=AAAAAA"+num);

            num=2;
            condition2.signal();//唤醒condition2
//            condition1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printB(){
        try {
            lock.lock();
            while (num!=2){
                condition2.await();
//                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=BBBBBB"+num);
            num=3;
            condition3.signal();
//            condition1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public void printC(){
        try {
            lock.lock();
            while (num!=3){
                condition3.await();
//                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=CCCCCC"+num);
            num=1;
            condition1.signal();
//            condition1.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}